package com.glsc.ngateway.opmanage.service.report.excel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.Cell;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.glsc.ngateway.common.base.domain.postgre6.TrsGtjaGzb;
import com.glsc.ngateway.common.base.repo.postgre6.TrsGtjaGzbRepo;
import com.glsc.ngateway.common.base.utils.ExcelDoubleConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author: qiyr
 * @date: 2023/4/4 13:57
 * @description: 国君TRS估值表
 */
public class TrsGtjaGzbListener extends AnalysisEventListener<Map<Integer, String>> {

    private static final Logger logger = LoggerFactory.getLogger(TrsGtjaGzbListener.class);
    private static final int BATCH_COUNT = 3000;
    private static final String TRDNO_PREFIX = "GTJA";
    List<TrsGtjaGzb> list = new ArrayList<>();

    private TrsGtjaGzbRepo trsGtjaGzbRepo;
    private Boolean clearFlag = false;
    private String date;

    public String getDate() {
        return date;
    }

    public TrsGtjaGzbListener() {
    }

    public TrsGtjaGzbListener(TrsGtjaGzbRepo trsGtjaGzbRepo) {
        this.trsGtjaGzbRepo = trsGtjaGzbRepo;
    }

    /**
     * 解析规则：
     * 估值日期：解析单元格B6
     *
     * @param data
     * @param analysisContext
     */
    @Override
    public void invoke(Map<Integer, String> data, AnalysisContext analysisContext) {
        ReadRowHolder readRowHolder = analysisContext.readRowHolder();
        Map<Integer, Cell> cellMap = readRowHolder.getCellMap();
        Integer rowIndex = readRowHolder.getRowIndex();

        if (rowIndex == 1) {
            date = data.get(0);
        } else if (rowIndex > 1 && StringUtils.hasText(data.get(2)) && data.get(2).startsWith(TRDNO_PREFIX)) {
            list.add(new TrsGtjaGzb(date, data.get(1), data.get(2), data.get(3),
                    ExcelDoubleConverter.cellToDouble(cellMap,4), data.get(5), data.get(6), data.get(7),
                    ExcelDoubleConverter.cellToDouble(cellMap,8), ExcelDoubleConverter.cellToDouble(cellMap,9),
                    ExcelDoubleConverter.cellToDouble(cellMap,10)));
        }

        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (list.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            list.clear();
        }
    }

    //读取完成之后
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }

    private void saveData() {
        if (!clearFlag) {
            clearFlag = true;
            trsGtjaGzbRepo.delete(date);
        }
        trsGtjaGzbRepo.saveAllAndFlush(list);
    }

}
